﻿using OPCAutomation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HelpLibrary.MyLog;

namespace HelpLibrary.OPCHelper
{
    public static class MyOPCItems
    {
        private static int _clintID;
        public static OPCItem CurrentopcItem;
        public static Dictionary<int, MyOPCItem> OPCTagDict = new Dictionary<int, MyOPCItem>();


        public static int ClintID
        {
            get => _clintID++;
            set => _clintID = value;
        }

        public static List<MyOPCItem> Bindlist { get; set; }

        /// <summary>
        /// 添加opc标签
        /// </summary>
        /// <param name="oPCItems">OPCItem集合</param>
        /// <param name="itemTagName">OPC标签名称</param>
        public static OPCItem AddItem(OPCItems oPCItems, string itemTagName)
        {
            try
            {
                CurrentopcItem = oPCItems.AddItem(itemTagName, _clintID);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            var mitem = new MyOPCItem
                {ServerHandle = CurrentopcItem.ServerHandle, ClintID = _clintID, ItemTag = itemTagName};
            OPCTagDict.Add(_clintID, mitem);
            _clintID++;
            return CurrentopcItem;
        }
        /// <summary>
        /// 移除opc标签
        /// </summary>
        /// <param name="oPCItems"></param>
        /// <param name="itemTagName"></param>
        public static void RemoveItem(OPCItems oPCItems, string itemTagName)
        {
            var getitem = GetOPCItemByTag(itemTagName);
            if (getitem != null)
            {
                var temp = new int[2] {0, getitem.ServerHandle};
                var serverHandle = (Array) temp;
                Array errors;
                oPCItems.Remove(1, ref serverHandle, out errors);
                OPCTagDict.Remove(getitem.ClintID);
            }
            else
            {
                MyLogHelper.LogHelper.WriteError("删除无效的节点");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="itemTagName"></param>
        /// <returns></returns>
        public static MyOPCItem GetOPCItemByTag(string itemTagName)
        {
            foreach (var myOPCItem in OPCTagDict)
                if (myOPCItem.Value.ItemTag == itemTagName)
                    return myOPCItem.Value;

            return null;
        }


        public static MyOPCItem FindItem(int clintId)
        {
            if (OPCTagDict[clintId] != null) return OPCTagDict[clintId];
            return new MyOPCItem();
        }
        /// <summary>
        /// 生成标签数组对象
        /// </summary>
        /// <returns></returns>
        public static List<MyOPCItem> GenerateBindlist()
        {
            Bindlist = OPCTagDict.Values.ToList();
            return Bindlist;
        }
    }
}